package cs342.uwosh.edu.MyWorldApp;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;

import cs342.uwosh.edu.R;
import cs342.uwosh.edu.MyWorldApp.cloud.CloudLinker;
import cs342.uwosh.edu.MyWorldApp.misc.AsyncMethod;
import cs342.uwosh.edu.MyWorldApp.misc.BackgroundMethod;
import cs342.uwosh.edu.MyWorldApp.storage.Friend;
import cs342.uwosh.edu.MyWorldApp.storage.User;
import cs342.uwosh.edu.MyWorldApp.storage.Location;

import android.app.ActionBar;
import android.app.ActionBar.Tab;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class FriendsListActivity extends Activity {
	
	private ListView listView;
	private User currentUser;
	private String searchString;
	private static final String EMPTY_HEADER  = "Add Friend +";
	
	
	
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
	    setContentView(R.layout.friends_list);
	    
		// Retrieve data from other activities
		Intent myIntent = getIntent();
		currentUser = myIntent.getParcelableExtra("user");  
		searchString = myIntent.getStringExtra("searchString");
		ArrayList<Friend> friendsList = null;
		
		// Create friends list
		if(searchString == null) {
			friendsList = currentUser.getFriendsList();
		} else {
			friendsList = new ArrayList<Friend>();
			ArrayList<Friend> myFriendsList = currentUser.getFriendsList();
			for(Friend f: myFriendsList) {
				if(f.getUserName().contains(searchString)) {
					friendsList.add(f);
				}
			}
		}
		
		
		
	    listView =  (ListView)findViewById(R.id.listView);
	    
		listView.setOnItemClickListener(new OnItemClickListener() {
	    	public void onItemClick(AdapterView<?> parent, View view,
	    	        int position, long id) {
	    		Object obj = listView.getItemAtPosition(position);
	    		if(obj instanceof String && ((String)obj).equals(EMPTY_HEADER)) {
    				addFriendPopup();
	    		}
	    	}
	    });
		
	    if(friendsList.size()>0) {
	    	/*ArrayAdapter<Friend> arrayAdapter;
	    	Friend[] friends = (Friend[])friendsList.toArray();
	        arrayAdapter = new ArrayAdapter<Friend>(this, R.layout.friends, friends);
	        listView.setAdapter(arrayAdapter);*/
	    } else {
	    	ArrayAdapter<String> arrayAdapter;
	    	
	    	String[] suggestion = new String[]{EMPTY_HEADER};
	    	
	    	arrayAdapter = new ArrayAdapter<String>(this, R.layout.friends, suggestion);
	        listView.setAdapter(arrayAdapter); 
	    }
	}
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.friends_list_menu, menu);
		return true;
	}

	public boolean onOptionsItemSelected(MenuItem item) {
		ArrayList<Friend> friendsList;
		int pos;
		switch (item.getItemId()) {
			case R.id.addMenu:
				addFriendPopup();
				break;
			case R.id.goToMenu:
				pos = listView.getCheckedItemPosition();
				if(pos != ListView.INVALID_POSITION) {
					friendsList = currentUser.getFriendsList();
					goToFriend(friendsList.get(pos));
				}
				break;
			case R.id.deleteMenu:
				pos = listView.getCheckedItemPosition();
				if(pos != ListView.INVALID_POSITION) {
					deleteFriend(pos);
					reloadActivity();
				}
				break;
		}
		return true;
	}
	
	public void addFriendPopup() {
		AlertDialog.Builder alert = new AlertDialog.Builder(this);

        alert.setTitle("Add Friend");
        alert.setMessage("Input a Username:");

        // Set an EditText view to get user input 
		final EditText inputBox = new EditText(this);
		alert.setView(inputBox);

		alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {
				String username = inputBox.getText().toString();
				if(username != null && !username.isEmpty()) {
					if(canAddFriend(username)) {
						addFriend(username);
						reloadActivity();
					}
				}
			}
		});

		alert.setNegativeButton("Cancel",
			new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int whichButton) {
					// Canceled.
				}
			});
		alert.show();
	}
	
	public boolean canAddFriend(String username) {
		/*Friend friend = new Friend(username, null);
		if(Collections.binarySearch(currentUser.getFriendsList(),friend) >= 0) {
			return false;
		} else {
			// TODO
			// check if user exists in cloud
		}
		return false;*/
		
		
		//THE CHECK FOR THIS IS TAKEN CARE OF IN THE CLOUD
		//An error will result if it cannot happen there.
		return true;
	}
	
	public String addFriend(String username) {
    	CloudLinker l = new CloudLinker(getBaseContext());
    	AsyncMethod<CloudLinker> a = new AsyncMethod<CloudLinker>(CloudLinker.class, l, "addFriend");
    	Intent myIntent = getIntent();
		currentUser = myIntent.getParcelableExtra("user");
    	a.execute(currentUser.getUserName(),username);
    	String response = (String)a.getResult();
		Toast.makeText(getBaseContext(), response,
				Toast.LENGTH_LONG).show();
		AsyncMethod<CloudLinker> a2 = new AsyncMethod<CloudLinker>(CloudLinker.class, l,"initializeUser");
		a2.execute(currentUser.getUserName());
		currentUser = (User)a2.getResult();
		return response;
	}
	
	public void goToFriend(Friend friend) {
		BackgroundMethod.forceUpdateAll();
		Intent myIntent = new Intent(this,
				MyWorldAppActivity.class);
		myIntent.putExtra("user", currentUser);
		myIntent.putExtra("friend", friend.getUserName());
		startActivity(myIntent);
		finish();
	}
   
    public void deleteFriend(int pos) {
    	// Remove from local list
    	Friend friend = currentUser.getFriendsList().remove(pos);
    	
    	//TODO Delete query
    	
    }
    public void reloadActivity() {
    	Intent myIntent = new Intent(this,
				FriendsListActivity.class);
		myIntent.putExtra("user", currentUser);
		startActivity(myIntent);
		finish();
    }
    
    public void onBackPressed() {
    	//BackgroundMethod.forceUpdateAll();
    	Intent myIntent = new Intent(this,
				MyWorldAppActivity.class);
		myIntent.putExtra("user", currentUser);
		startActivity(myIntent);
    	super.onBackPressed();
    }
}
